package com.ebring.shareEducation.controller;

import com.ebring.shareEducation.bean.Video;
import com.ebring.shareEducation.bean.VideoOrder;
import com.ebring.shareEducation.service.VideoOrderService;
import com.ebring.shareEducation.service.VideoService;
import com.ebring.shareEducation.util.VideoThumbTaker;
import com.ebring.shareEducation.utils.RspMsg;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by Cola
 * Date  2018-12-14 09:09
 */
@RestController
public class VideoController {

    @Autowired
    VideoService videoService;

    @Autowired
    VideoOrderService videoOrderService;

  /*  @Autowired
    CoinOrderService coinOrderService;*/

    private static Logger logger = LoggerFactory.getLogger(VideoController.class);

    /**
     * 视频上传
     *
     * @param file     文件
     * @param request
     * @param response
     * @param userId   用户id
     * @return
     * @throws IllegalStateException
     * @throws IOException
     */

    @PostMapping("/video/Upload")
    public RspMsg<Object> videoUpload(MultipartFile file, HttpServletRequest request, HttpServletResponse response, String userId) throws IllegalStateException, IOException {
        RspMsg<Object> rspMsg = new RspMsg<>();
        if (file != null) {// 判断上传的文件是否为空

            long len = file.getSize();//上传文件的大小, 单位为字节.
            // 准备接收换算后文件大小的容器
            double fileSize = 0;

            // 设定视频文件上传大小，默认为1G
            fileSize = (double) len / 1073741824;

            // 如果上传文件大于限定的容量
            if (fileSize > 1) {
                rspMsg.setError();
                logger.info("视频文件超出上传限制");
                rspMsg.setMsg("视频文件超出上传限制");
                return rspMsg;
            }

            String path = null;// 文件路径
            String type = null;// 文件类型
            String fileName = file.getOriginalFilename();// 文件原名称
            logger.info("上传的文件原名称:" + fileName);
            // 判断文件类型
            type = fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()) : null;
            if (type != null) {// 判断文件类型是否为空
                if ("MP4".equals(type.toUpperCase()) || "MOV".equals(type.toUpperCase())) {
                    // 项目在容器中实际发布运行的根路径
                    String realPath = request.getSession().getServletContext().getRealPath("/");
//                    String realPath = "/picUpload";
                    // 自定义的文件名称
                    String trueFileName = String.valueOf(System.currentTimeMillis()) + fileName;
                    // 设置存放图片文件的路径
//                    path = realPath +/*System.getProperty("file.separator")+*/trueFileName;
//                    path = "/Users/cola/Desktop/测试文件上传/" + trueFileName;
//                    System.out.println("存放视频文件的路径:" + path);

                    // 格式化文件夹名称，精确到月份
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyyMM");
                    Date date = new Date();
                    String month = formatter.format(date);

                    // 文件所保存文件夹路径
                    String directory = "D:\\EbringCode\\server\\apache-tomcat-9.0.13\\webapps\\test\\" + month;

                    // 文件夹名称精确到月份
                    File file1 = new File(directory);
                    // 判断文件夹是否存在
                    if (file1.exists()) {
                        if (file1.isDirectory()) {
                            logger.info("dir exists");
                        } else {
                            logger.info("the same name file exists, can not create dir");
                        }
                    } else {
                        logger.info("dir not exists, create it ...");
                        file1.mkdirs();

                    }

                    // 文件夹名称精确到个人
                    File file2 = new File(directory + '/' + userId);
                    // 判断文件夹是否存在
                    if (file2.exists()) {
                        if (file2.isDirectory()) {
                            logger.info("dir exists");
                        } else {
                            logger.info("the same name file exists, can not create dir");
                        }
                    } else {
                        logger.info("dir not exists, create it ...");
                        file2.mkdirs();

                    }

                    // 转存文件到指定的路径
                    // String jar_v4 = new String(file2.getPath().getBytes(), "UTF-8");
                    file.transferTo(new File(file2 + File.separator + trueFileName));
                    String httpVideoPath = "http://192.168.108.68:8020/test/" + month + '/' + userId + '/' + trueFileName;
                    rspMsg.setOK();
                    logger.info("文件的保存地址：" + httpVideoPath);
                    // 保存视频的某一张图片，用于显示在视频列表
                    String videoImg = trueFileName.substring(0, trueFileName.lastIndexOf("."));
                    VideoThumbTaker videoThumbTaker = new VideoThumbTaker("C:\\Users\\41879\\Downloads\\ffmpeg-20181223-bb586a9-win64-static\\bin\\ffmpeg.exe");
                    try {
                        videoThumbTaker.getThumb(directory + File.separator + userId + File.separator + trueFileName, directory + File.separator + userId + File.separator + videoImg + ".png", 800, 600, 0, 0, 5);
                        logger.info("over");
                        String VideoImgPath = "http://192.168.108.68:8020/test/" + month + '/' + userId + '/' + videoImg + ".png";
                        rspMsg.setResult(httpVideoPath + "," + VideoImgPath);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    rspMsg.setError();
                    logger.info("不是我们想要的文件类型,请按要求重新上传");
                    rspMsg.setMsg("不是我们想要的文件类型,请按要求重新上传");
                }
            } else {
                rspMsg.setError();
                logger.info("文件类型为空");
                rspMsg.setMsg("文件类型为空");
            }
        } else {
            rspMsg.setError();
            logger.info("没有找到相对应的文件");
            rspMsg.setMsg("没有找到相对应的文件");
        }
        return rspMsg;
    }


    /**
     * 视频文件上传记录
     *
     * @param video 实体对象
     * @return
     */

    @PostMapping("/video/submit")
    public RspMsg<Video> insert(Video video) {
        return videoService.insert(video);
    }

    /**
     * 购买视频
     *
     * @param buyId   购买人ID
     * @param videoId 视频ID
     * @return
     */
    @PostMapping("/video/buy")
    public RspMsg insert(String buyId, String videoId) {
        RspMsg rspMsg = new RspMsg();
        RspMsg<Video> videoRspMsg = videoService.selectById(videoId);
      /*  if (videoRspMsg.getCode() == 1) {
            // 获取视频对象
            Video video = videoRspMsg.getResult();
            CoinOrder coinOrder = new CoinOrder();
            // 扣买家金币
            coinOrder.setUserId(buyId);
            coinOrder.setAmount(video.getMoney());
            rspMsg = coinOrderService.minusMoney(coinOrder);
            // 增卖家金币
            coinOrder.setUserId(video.getUserId());
            RspMsg rspMsg1 = coinOrderService.addMoney(coinOrder);
            VideoOrder videoOrder = new VideoOrder();
            videoOrder.setBuyId(buyId);
            videoOrder.setVideoId(videoId);
            videoOrder.setMoney(video.getMoney());
            videoOrder.setUserId(video.getUserId());
            // 记录购买视频流水
            return videoOrderService.insert(videoOrder);

        }*/

        return videoRspMsg;

    }

    /**
     * 查询购买视频记录
     *
     * @param videoOrder
     * @return
     */
    @PostMapping("/videoorder/select")
    public RspMsg<VideoOrder> select(VideoOrder videoOrder) {
        return videoOrderService.select(videoOrder);
    }

    /**
     * 获取视频列表
     *
     * @return
     */
    @GetMapping("/video/select")
    public RspMsg<Video> select() {
        return videoService.select();
    }
}

